<template>
  <Modal
      :body-style="{ paddingBottom: '80px' }"
      :footer-style="{ textAlign: 'right' }"
      :title="subProps.title"
      :visible="subProps.visible"
      :width="720"
      @cancel="onClose"
  >
    <Form ref="formRef" :model="form" :rules="rules" autocomplete="off" layout="vertical">
      <Row :gutter="24">
        <Col :span="20">
          <FormItem
              v-if="subProps.drawerType === 'topic'"
              :allowClear="true"
              label="订阅主题名"
              name="Urn"
          >
            <Input v-model:value="topicUrn" disabled/>
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="24">
        <Col :span="20">
          <FormItem v-if="subProps.drawerType === 'subscript'" label="订阅主题名" name="topicUrn">
            <Select
                v-model:value="form.topicUrn"
                :field-names="{ label: 'topicName', value: 'topicUrn' }"
                :options="selectOptions"
            ></Select>
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :span="12">
          <FormItem label="订阅协议" name="protocol">
            <Select
                v-model:value="form.protocol"
                :allowClear="true"
                placeholder="Please choose the protocol"
            >
              <SelectOption value="email">邮件</SelectOption>
              <SelectOption value="sms">短信</SelectOption>
            </Select>
          </FormItem>
        </Col>
      </Row>
    </Form>
    <Button class="editable-add-btn" style="margin-bottom: 8px" @click="handleAdd"
    >添加订阅终端
    </Button
    >
    <Table
        :columns="endpointColumns"
        :dataSource="endpointDataSource"
        :pagination="false"
        :rules="rules"
        bordered
    >
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.key === 'endpoint'">
          <Input
              v-model:value="endpointDataSource[index].endpoint"
              placeholder="xxx@xxx.com/13088885656"
              style="display: flex"
          />
        </template>
        <template v-if="column.key === 'remark'">
          <Input v-model:value="endpointDataSource[index].remark" style="display: flex"/>
        </template>
        <template v-if="column.dataIndex === 'operation'">
          <Popconfirm
              v-if="endpointDataSource.length" cancel-text="取消"
              ok-text="确认"
              title="确定要删除吗?"
              @confirm="onDelete(record.key)"
          >
            <a>删除</a>
          </Popconfirm>
        </template>
      </template>
    </Table>

    <template #footer>
      <Space>
        <Button @click="onClose">取消</Button>
        <Button type="primary" @click="onSub">提交</Button>
      </Space>
    </template>
  </Modal>
</template>
<script lang="ts" setup>
import {
  Button,
  Col,
  Form,
  FormItem,
  Input,
  message,
  Modal,
  Popconfirm,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
} from 'ant-design-vue';
import {endpointColumns, form,} from '/@/views/maintenance-center/message-theme/components/subscription';
import {computed, Ref, ref} from 'vue';
import {EndpointList} from '/@/api/maintenance-center/message-notification/model/messageNotificationModel';
import {createSubscription} from '/@/api/maintenance-center/message-notification/messageNotification';
import {Rule} from 'ant-design-vue/es/form';

const formRef = ref();
let endpointDataSource: Ref<EndpointList[]> = ref([]);
const subProps = defineProps({
  visible: Boolean,
  drawerType: String,
  title: String,
  URN: String,
  topicName: String,
  selectOptions: {},
});
// 通知父组件修改值
let topicUrn = computed(() => subProps.URN);
const emits = defineEmits(['closeSubDrawer']);
const onClose = () => {
  formRef.value.resetFields();
  endpointDataSource.value = [];
  emits('closeSubDrawer');
};
// 添加订阅
const count = computed(() => endpointDataSource.value.length + 1);
const handleAdd = () => {
  const header = {
    key: `${count.value}`,
    endpoint: '',
    remark: '',
  };
  endpointDataSource.value.push(header);
};
const onDelete = (key: string) => {
  endpointDataSource.value = endpointDataSource.value.filter((item) => item.key !== key);
};
const onSubmit = () => {
  return formRef.value.validate();
};
const checkTable = () => {
  let flag = 0;
  if (endpointDataSource.value.length === 0) {
    flag = 1;
  } else if (form.protocol === 'email') {
    endpointDataSource.value.some((endpoint) => {
      flag =
          endpoint.endpoint === '' || endpoint.remark === ''
              ? 2
              : endpoint.endpoint.match('\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*')
                  ? 0
                  : 3;
      return flag;
    });
  } else if (form.protocol === 'sms') {
    endpointDataSource.value.some((endpoint) => {
      flag =
          endpoint.endpoint === '' || endpoint.remark === ''
              ? 2
              : endpoint.endpoint.match('1\\d{10}')
                  ? 0
                  : 3;
      return flag;
    });
  }
  return flag;
};
const onSub = () => {
  onSubmit()
      .then(() => {
        let flag = checkTable();
        if (flag == 1) {
          throw message.error('请添加订阅终端');
        }
        if (flag == 2) {
          throw message.error('订阅终端和备注均为必填项');
        }
        if (flag == 3) {
          throw message.error('订阅终端格式不正确');
        }
      })
      .then(() => {
        let topicURN = '';
        if (subProps.drawerType === 'subscript') {
          topicURN = form.topicUrn;
        } else if (subProps.drawerType === 'topic') {
          topicURN = String(topicUrn.value);
        }

        const param = {
          topicUrn: topicURN,
          protocol: form.protocol,
          endpointList: endpointDataSource.value,
        };

        createSubscription(param)
            .then(() => {
              message.success('添加订阅成功');
            })
            .catch((e) => {
              message.error('添加订阅失败' + e.response.data.msg);
            });
        onClose();
      });
};
// 校验
const rules: Record<string, Rule[]> = {
  protocol: [{required: true, message: 'Please enter protocol'}],
  topicUrn: [{required: true, message: 'Please enter topicUrn'}],
  endpoint: [{required: true, message: 'Please enter endpoint'}],
};
</script>